
package com.hockeo.tinygds;

import java.lang.reflect.Field;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.hockeo.tinygds.error.TinyGDSException;

/**
 * Represents a Long primary key field.
 * 
 * @version $Id$
 * @author jjanke
 */
public class TFieldPkLong extends TFieldPrimaryKey<Long>
{

  protected TFieldPkLong( TinyGDSFactory factory, Field field )
  {
    super( factory, field );
  }

  public Entity createEntity( Object instance, String strKind, Key keyParent )
  {
    Long lId = getValue( instance );
    
    if ( lId == null )
    {
      // key will be auto-generated when entity is persisted
      //
      return new Entity( strKind, keyParent );
    }
    else
      return new Entity( KeyFactory.createKey( keyParent, strKind, lId ) );
  }
  
  public Key getKey( Object objInstance, String strKind, Key keyParent )
  {
    Long lId = getValue( objInstance );

    if ( lId == null )
      throw new TinyGDSException( "It is not allowed to create a Key for an object with a null "
          + "@Id value. The object is " + objInstance.toString() );
    
    return KeyFactory.createKey( keyParent, strKind, lId );
  }
  
  public void setKey( Object objInstance, Key key )
  {
    // Only set the id if the key is marked as complete
    //
    if ( key.isComplete() )
      setValue( objInstance, key.getId() );
  }
}
